package cc.verywell.pureblock.msg.nfs.linkmap;

import java.io.Closeable;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.atomic.AtomicLong;

/**
* 
* Copyright © 2019 TanYaqiu. All rights reserved.
* @author TanYaqiu 
* @address flat 601
* @date 2019年6月16日 下午3:36:05
*/
public class EasyTableMem implements EasyTable,Closeable {

	final ConcurrentSkipListSet<LinkCell> map;
	final EasyTableMemLog log;
	final long fileNumber;
	private boolean closed = false;
	
	public EasyTableMem(long fileNumber,EasyTableMemLog log) {
		this(fileNumber,new ConcurrentSkipListSet<>(),log);
	}
	EasyTableMem(long fileNumber,ConcurrentSkipListSet<LinkCell> map,EasyTableMemLog log){
		this.fileNumber = fileNumber;
		this.map = map;
		this.log = log;
	}
	@Override
	public void close(){
		if(closed)return;
		closed = true;
		log.close();
	}
	public void delete() {
		close();
		log.delete();
	}

	@Override
	public EasyIterator get(LinkCell startWith) {
		LinkCell lc = map.ceiling(startWith);
		if(lc==null || !lc.startWith(startWith))return null;
		Iterator<LinkCell> it = map.tailSet(lc, true).iterator();
		if(!it.hasNext())return null;
		return new EasyTableMemIterator(it,startWith);
	}
//	@Override
//	public boolean has(LinkCell startWith) {
//		EasyIterator it = get(startWith);
//		if(it==null)return false;
//		
//		LinkCell last = it.next();
//		if(last==null)return false;
//		else if(last.isRemove()) {
//		}else return true;
//		
//		LinkCell nxt;
//		while(null!=(nxt=it.next())) {
//			if(!nxt.equalsWithoutSeq(last, 0)) {
//				if(nxt.isRemove()) {
//					last = nxt;
//				}else {
//					return true;
//				}
//			}
//		}
//		
//		return false;
//	}
	
	public void add(LinkCell add) {
		log.add(add);
		map.add(add);
	}
	public void addAll(Collection<? extends LinkCell>  adds) {
		log.addAll(adds);
		map.addAll(adds);
	}
	
	static private class EasyTableMemIterator implements EasyIterator{

		protected Iterator<LinkCell> it;
		protected LinkCell startWith;
		protected LinkCell current;
		public EasyTableMemIterator(Iterator<LinkCell> it,LinkCell startWith) {
			this.it = it;
			this.startWith = startWith;
			next();
		}

		@Override
		public boolean hasNext() {
			return current!=null || (it!=null && it.hasNext());
		}

		@Override
		public LinkCell next() {
			LinkCell cr = current;
			current = null;
			while(it!=null && it.hasNext()) {
				LinkCell nxt = it.next();
				if(nxt.startWith(startWith)) {
					if(!nxt.equalsWithoutSeq(cr,startWith.encoded.length)) {
						current = nxt;
						break;
					}
				}else {
					it = null;
				}
			}
			return cr;
		}

		@Override
		public LinkCell current() {
			return current;
		}
		
		

	}

}
